<template>
  <demoBlock title="校验规则">
    <vcu-form @submit="onSubmit" @failed="onFailed">
      <vcu-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <vcu-input
          v-model="value1"
          label="label1"
          name="pattern"
          placeholder="正则校验"
          :rules="[{ pattern, message: '请输入正确内容' }]"
        />
        <!-- 通过 validator 进行函数校验 -->
        <vcu-input
          v-model="value2"
          label="label2"
          name="validator"
          placeholder="函数校验"
          :rules="[{ validator, message: '请输入正确内容' }]"
        />
        <!-- 通过 validator 返回错误提示 -->
        <vcu-input
          v-model="value3"
          label="label3"
          name="validatorMessage"
          placeholder="校验函数返回错误提示"
          :rules="[{ validator: validatorMessage }]"
        />
        <!-- 通过 validator 进行异步函数校验 -->
        <vcu-input
          v-model="value4"
          label="label4"
          name="asyncValidator"
          placeholder="异步函数校验"
          :rules="[{ validator: asyncValidator, message: '请输入正确内容' }]"
        />
      </vcu-cell-group>
      <div style="margin: 16px">
        <vcu-button round block type="primary" native-type="submit">
          提交
        </vcu-button>
      </div>
    </vcu-form>
  </demoBlock>
</template>

<script>
import { defineComponent, ref } from "vue";
import { Toast } from "../../../components";

export default defineComponent({
  setup() {
    const value1 = ref("");
    const value2 = ref("");
    const value3 = ref("");
    const value4 = ref("");
    const pattern = /\d{6}/;

    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator = (val) => /1\d{10}/.test(val);

    // 校验函数可以直接返回一段错误提示
    const validatorMessage = (val) => `${val} 不合法，请重新输入`;

    // 校验函数可以返回 Promise，实现异步校验
    const asyncValidator = (val) =>
      new Promise((resolve) => {
        Toast.loading("验证中...");

        setTimeout(() => {
          Toast.clear();
          resolve(/\d{6}/.test(val));
        }, 1000);
      });

    const onSubmit = (values) => {
      console.log("submit", values);
    };
    const onFailed = (errorInfo) => {
      console.log("failed", errorInfo);
    };

    return {
      value1,
      value2,
      value3,
      value4,
      pattern,
      validatorMessage,
      onFailed,
      validator,
      asyncValidator,
      onSubmit
    };
  },
});
</script>
